package xdu.lz.stage2_design_pattern.chapter16_two_phrase_terminated_pattern;

import java.io.*;
import java.net.Socket;

public class ClientHandler implements Runnable{

    private final Socket socket;

    private volatile boolean running = true;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        //实现了closeable接口 ，直接try会自动关闭
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream();
             //先把字节流转字符串，然后用缓冲字符流封装
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
             //把输出字节流转为打印字符流，专门向文件输出的流
            PrintWriter writer = new PrintWriter(outputStream)){

            while (running){
                String msg = br.readLine();
                if(msg == null){
                    break;
                }
                System.out.println("come from client "+msg);
                writer.write("echo "+msg+"\r\n");
                writer.flush();
            }

        }catch (IOException e){
            //当服务端关闭后，客户端就会出现IO异常
            System.out.println("服务端强制关闭，客户端出现了IO异常");
            this.running = false;
        }finally {
            System.out.println("客户端被关闭了，释放资源...");
            this.stop();
        }


    }

    public void stop() {

        //如果还没跑完  或者 客户端已经挂掉。如不不加，this.socket可能会出现空指针
        if(!running){
            return;
        }
        //
        this.running = false;
        try {
            this.socket.close();
        } catch (IOException e) {
            System.out.println("关闭socket出现异常");
        }
    }
}
